import { defineStore } from 'pinia';
import { exerciseApi, cardApi } from '@/services/api';

export const useExerciseStore = defineStore('exercise', {
  state: () => ({
    exercises: [],
    currentExercise: null,
    userAnswers: {},
    results: {},
    stats: null,
    loading: false,
    error: null,
    filters: {
      type: null, // 'multiple-choice', 'fill-in-blank', 'coding'
      difficulty: null,
      topic: null,
      search: '',
    },
    pagination: {
      page: 1,
      limit: 10,
      total: 0,
    },
  }),
  
  getters: {
    getExercises: (state) => state.exercises,
    getCurrentExercise: (state) => state.currentExercise,
    getUserAnswers: (state) => state.userAnswers,
    getResults: (state) => state.results,
    getStats: (state) => state.stats,
    isLoading: (state) => state.loading,
    getError: (state) => state.error,
    getFilters: (state) => state.filters,
    getPagination: (state) => state.pagination,
    
    // 获取当前练习的用户答案
    getCurrentAnswer: (state) => {
      if (!state.currentExercise) return null;
      return state.userAnswers[state.currentExercise._id];
    },
    
    // 获取当前练习的结果
    getCurrentResult: (state) => {
      if (!state.currentExercise) return null;
      return state.results[state.currentExercise._id];
    },
  },
  
  actions: {
    // 获取练习题列表
    async fetchExercises() {
      this.loading = true;
      this.error = null;
      
      try {
        const params = {
          page: this.pagination.page,
          limit: this.pagination.limit,
          ...this.filters,
        };
        
        const response = await exerciseApi.getExercises(params);
        this.exercises = response.data.exercises;
        this.pagination.total = response.data.total;
        
        return { success: true, exercises: this.exercises, total: response.data.total };
      } catch (error) {
        this.error = error.response?.data?.message || '获取练习题失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 获取随机练习题
    async fetchRandomExercises(params = {}) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await exerciseApi.getRandomExercises({
          ...this.filters,
          ...params,
        });
        this.exercises = response.data;
        
        return { success: true, exercises: this.exercises };
      } catch (error) {
        this.error = error.response?.data?.message || '获取随机练习题失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 获取单个练习题详情
    async fetchExercise(exerciseId) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await exerciseApi.getExerciseById(exerciseId);
        this.currentExercise = response.data;
        
        return { success: true, exercise: this.currentExercise };
      } catch (error) {
        this.error = error.response?.data?.message || '获取练习题详情失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 获取卡片的练习题
    async fetchCardExercises(cardId) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await cardApi.getCardExercises(cardId);
        this.exercises = response.data;
        
        return { success: true, exercises: this.exercises };
      } catch (error) {
        this.error = error.response?.data?.message || '获取卡片练习题失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 为卡片生成练习题
    async generateCardExercises(cardId, options = {}) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await cardApi.generateCardExercises(cardId, options);
        this.exercises = response.data;
        
        return { success: true, exercises: this.exercises };
      } catch (error) {
        this.error = error.response?.data?.message || '生成练习题失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 提交答案
    async submitAnswer(exerciseId, userAnswer) {
      this.loading = true;
      this.error = null;
      
      try {
        // 保存用户答案
        this.userAnswers = {
          ...this.userAnswers,
          [exerciseId]: userAnswer,
        };
        
        const response = await exerciseApi.checkExerciseAnswer(exerciseId, userAnswer);
        
        // 保存结果
        this.results = {
          ...this.results,
          [exerciseId]: response.data,
        };
        
        return { success: true, result: response.data };
      } catch (error) {
        this.error = error.response?.data?.message || '提交答案失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 获取用户练习统计
    async fetchUserStats() {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await exerciseApi.getUserExerciseStats();
        this.stats = response.data;
        
        return { success: true, stats: this.stats };
      } catch (error) {
        this.error = error.response?.data?.message || '获取练习统计失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 更新练习题
    async updateExercise(exerciseId, exerciseData) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await exerciseApi.updateExercise(exerciseId, exerciseData);
        
        // 更新当前练习题
        if (this.currentExercise && this.currentExercise._id === exerciseId) {
          this.currentExercise = response.data;
        }
        
        // 更新练习题列表中的练习题
        const index = this.exercises.findIndex(exercise => exercise._id === exerciseId);
        if (index !== -1) {
          this.exercises[index] = response.data;
        }
        
        return { success: true, exercise: response.data };
      } catch (error) {
        this.error = error.response?.data?.message || '更新练习题失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 删除练习题
    async deleteExercise(exerciseId) {
      this.loading = true;
      this.error = null;
      
      try {
        await exerciseApi.deleteExercise(exerciseId);
        
        // 从练习题列表中移除
        this.exercises = this.exercises.filter(exercise => exercise._id !== exerciseId);
        
        // 如果当前练习题是被删除的练习题，则清空当前练习题
        if (this.currentExercise && this.currentExercise._id === exerciseId) {
          this.currentExercise = null;
        }
        
        return { success: true };
      } catch (error) {
        this.error = error.response?.data?.message || '删除练习题失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 设置过滤器
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters };
      this.pagination.page = 1; // 重置页码
      return this.fetchExercises();
    },
    
    // 设置分页
    setPagination(pagination) {
      this.pagination = { ...this.pagination, ...pagination };
      return this.fetchExercises();
    },
    
    // 清除用户答案和结果
    clearAnswers() {
      this.userAnswers = {};
      this.results = {};
    },
    
    // 重置状态
    resetState() {
      this.exercises = [];
      this.currentExercise = null;
      this.userAnswers = {};
      this.results = {};
      this.stats = null;
      this.loading = false;
      this.error = null;
      this.filters = {
        type: null,
        difficulty: null,
        topic: null,
        search: '',
      };
      this.pagination = {
        page: 1,
        limit: 10,
        total: 0,
      };
    },
  },
}); 